import requests
import socket
import logging
from datetime import datetime

from core.db_manager import execute_query, execute_update


class TeamCommander:
    def __init__(self):  # 配置日志
        logging.basicConfig(
            filename='sql.log',
            level=logging.INFO,
            format='%(asctime)s - %(message)s'
        )
        self.current_ip = self.get_local_ip()
        self.my_info = self.load_my_info()
        self.team_id = self.my_info['team_id']
        self.team_info = self.load_team_info(self.team_id)

    def _log_sql(self, sql, params=None, ret=None):
        """记录SQL查询到日志文件"""
        log_message = f"SQL: {sql}"
        if params:
            log_message += f" | Params: {params}"
        if ret:
            log_message += f" | Ret: {ret}"
        logging.info(log_message)

    # 获取本机局域网ip
    def get_local_ip(self):
        try:
            # 创建一个UDP套接字（不会真正发送数据）
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))  # 连接Google DNS
            ip = s.getsockname()[0]
            s.close()
            return ip
        except Exception:
            return "127.0.0.1"  # 失败返回本地回环地址

    # 设置开始状态 status=0
    def set_init_status(self):
        sql = "UPDATE game_team_info t1 JOIN (SELECT DISTINCT team_id FROM game_team_info WHERE ip=%s) t2 ON t1.team_id = t2.team_id SET t1.STATUS = 0"
        ret = execute_update(sql, self.current_ip)
        self._log_sql(sql, ret)
        return ret

    def load_my_info(self):
        """加载当前本机账号的数据库信息"""
        sql = "SELECT * FROM game_team_info WHERE ip=%s"
        ret = execute_query(
            sql,
            (self.current_ip,)
        )[0]  # 取第一条记录
        self._log_sql(sql, self.current_ip, ret)
        return ret

    # 获取队伍所有成员信息
    def load_team_info(self, team_id):
        sql = "SELECT * FROM game_team_info WHERE team_id=%s and is_leader=0"
        ret = execute_query(
            sql,
            (team_id,)
        )
        return ret

    # 获取队员准备好的列表
    def load_team_ready(self, team_id):
        sql = "SELECT * FROM game_team_info WHERE team_id=%s and status = 1 and is_leader=0 and status = 1"
        ret = execute_query(
            sql,
            (team_id,)
        )
        return ret

    # 设置进队状态 status=1
    def set_ready_status(self):
        sql = "UPDATE game_team_info SET STATUS = 1 WHERE ip =%s"
        ret = execute_update(sql, self.current_ip)
        self._log_sql(sql, ret)
        return ret

    # 邀请队友
    def invite_teammates(self, ip):
        url = "http://" + ip + ":5000/receive_invite"  # 替换为实际 API
        headers = {
            "Content-Type": "application/json",
        }

        try:
            response = requests.post(url, headers=headers)
            if response.status_code == 200:
                print(f"成功邀请 {ip} 的队友")
                return True
            else:
                print(f"邀请失败: {response.text}")
                return False
        except Exception as e:
            print(f"请求异常: {e}")
            return False

    # 通知开始时间
    def send_start_time(self, ip, start_time):
        url = "http://" + ip + ":5000/handle_start_game"
        headers = {
            "Content-Type": "application/json",
        }
        payload = {
            "start_time": start_time,  # 将秒值作为参数传递
        }
        requests.post(url, headers=headers, json=payload)

    def confirm_join(self, leader_ip):
        """队员确认加入队伍"""
        try:
            # 通知队长已加入
            requests.post(
                f"http://{leader_ip}:5000/confirm_join",
                json={'member_ip': self.current_ip},
                timeout=3
            )
            # 更新自身状态
            execute_update(
                "UPDATE game_team_info SET status=1 WHERE ip=%s",
                (self.current_ip,)
            )
            return True
        except requests.exceptions.RequestException:
            return False

    def check_team_ready(self):
        """检查队伍是否准备就绪"""
        members = execute_query(
            "SELECT status FROM game_team_info WHERE team_id=%s",
            (self.team_info['team_id'],)
        )
        return all(m['status'] == 2 for m in members)
